package com.ddd.demo.lee.test;

import java.util.HashMap;
import java.util.Map;

public class Solution3 {

    // 更好理解
    public int lengthOfLongestSubstring2(String s) {
        int result = 0;
        Map<Character,Integer> map = new HashMap<>();
        int i = 0;
        for (int j = 0; j < s.length(); j++) {
            i = Math.max(i,map.getOrDefault(s.charAt(j),0));
            result = Math.max(result,j - i +1);
            map.put(s.charAt(j),j + 1);
        }
        return result;
    }

    public static int lengthOfLongestSubstring(String s) {
        char[] chars = s.toCharArray();
        Map<Character,Integer> map = new HashMap<>();
        int max = 0;

        for (int start = 0,end = 0; end < chars.length; end++) {
            char right = chars[end];
            map.put(right,map.getOrDefault(right,0) + 1);

            while (map.get(right) > 1){ // 已经找到2个重复元素在子串的时候
                char left = s.charAt(start);
                map.put(left, map.get(left) -1);
                start++;
            }
            max = Integer.max(max,(end - start + 1));
        }

        return max;
    }

    public static void main(String[] args) {
        String s = "pwwkew";
        int i = lengthOfLongestSubstring(s);
        System.out.println("i = " + i);
    }
}
